package com.ming.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.ming.yygh.common.helper.HttpRequestHelper;
import com.ming.yygh.enums.OrderStatusEnum;
import com.ming.yygh.enums.PaymentStatusEnum;
import com.ming.yygh.enums.PaymentTypeEnum;
import com.ming.yygh.hosp.client.HospitalFeignClient;
import com.ming.yygh.model.order.OrderInfo;
import com.ming.yygh.model.order.PaymentInfo;
import com.ming.yygh.order.mapper.PaymentMapper;
import com.ming.yygh.order.service.OrderService;
import com.ming.yygh.order.service.PaymentService;
import com.ming.yygh.order.utils.ConstantPropertiesUtils;
import com.ming.yygh.order.utils.HttpClient;
import com.ming.yygh.vo.order.SignInfoVo;
import io.swagger.v3.oas.annotations.servers.Server;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Light
 * @date 2021/12/24 9:50
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {

    @Resource
    private OrderService orderService;

    @Resource
    private HospitalFeignClient hospitalFeignClient;

    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 根据订单id和支付类型，查询支付记录表是否存在相同订单
        Integer count = baseMapper.selectCount(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderInfo.getId())
                .eq("payment_type", paymentType));
        if (count > 0) {
            return;
        }
        // 添加记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        baseMapper.insert(paymentInfo);
    }

    @Override
    public void paySuccess(String outTradeNo, Map<String, String> resultMap) {
        // 1、根据订单编号得到支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", outTradeNo)
                .eq("payment_type", PaymentTypeEnum.WEIXIN.getStatus()));

        // 2、更新支付记录
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackContent(resultMap.toString());
        baseMapper.updateById(paymentInfo);

        // 3、根据订单得到订单信息
        OrderInfo orderInfo = orderService.getOrder(paymentInfo.getOrderId());

        // 4、更新订单信息
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);

        // 5、调用医院接口，更新订单支付信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode()).getData();
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
    }

    @Override
    public PaymentInfo getPaymentInfo(String orderId, Integer paymentType) {
        return baseMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId)
                .eq("payment_type", paymentType));
    }

}
